new Vue({
    el: '#app',
    data: {
        addresses: [],
        showModal: false, // 控制新建/编辑地址模态框显示
        editMode: false, // 判断当前是编辑模式还是新建模式
        currentAddress: { // 当前正在编辑或新建的地址数据
            addressId: '',
            name: '',
            phone: '',
            region: '',
            address: '',
            isDefault: false,
            province: '',
            city: '',
            district: '',
            countryCode: '+86'
        },
        provinces: [], // 省份列表数据
        cities: [], // 城市列表数据
        districts: [], // 区县列表数据
        showDeleteModal: false, // 控制删除确认弹窗显示 (虽然HTML注释了，数据和方法保留)
        addressToDelete: null // 待删除的地址对象 (保留)
    },
    methods: {
        // 获取用户ID
        getUserIdFromUrl() {
            const params = new URLSearchParams(window.location.search);
            return params.get('userId');
        },
        //获取用户的收获地址
        fetchAddresses() {
            // const userId = this.getUserIdFromUrl();
            $.ajax({
                url: `http://localhost:8080/address/findAllAddress`,
                type: 'POST',
                dataType: 'json',
                data: { userId: localStorage.getItem('userId') },
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (response) => {
                    if (response.code === 200 && Array.isArray(response.data)) {
                        this.addresses = response.data;
                    } else {
                        this.addresses = [];
                        alert('加载地址列表失败: ' + (response.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    this.addresses = [];
                }
            });
        },

        // 加载省份数据 (用于三级联动)
        loadProvinces() {
            $.ajax({
                url: "http://localhost:8080/api/province",
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (result) => {
                    this.provinces = result.list;
                }
            });
        },

        // 省份选择改变时加载城市
        onProvinceChange() {
            this.currentAddress.city = '';
            this.currentAddress.district = '';
            this.cities = [];
            this.districts = [];
            if (this.currentAddress.province) {
                $.ajax({
                    url: "http://localhost:8080/api/city",
                    type: 'GET',
                    data: { pname: this.currentAddress.province },
                    headers: { 'token': `${localStorage.getItem('token') || ''}` },
                    success: (result) => {
                        this.cities = result.list;
                    }
                });
            }
        },

        // 城市选择改变时加载区县
        onCityChange() {
            this.currentAddress.district = '';
            this.districts = [];
            if (this.currentAddress.province && this.currentAddress.city) {
                $.ajax({
                    url: "http://localhost:8080/api/area",
                    type: 'GET',
                    headers: { 'token': `${localStorage.getItem('token') || ''}` },
                    data: {
                        pname: this.currentAddress.province,
                        cname: this.currentAddress.city
                    },
                    success: (result) => {
                        this.districts = result.list;
                    }
                });
            }
        },

       // 打开新建地址模态框
        openNewAddress() {
            // 重置currentAddress数据
            this.currentAddress = {
                id: '',
                recipient: '',
                phone: '',
                region: '',
                detail: '',
                isDefault: false,
                province: '',
                city: '',
                district: '',
                countryCode: '+86'
            };
            this.editMode = false;
            this.showModal = true;

            // 清空城市和区县下拉框数据
            this.cities = [];
            this.districts = [];
            // 确保省份下拉框加载了数据
            if (this.provinces.length === 0) {
                this.loadProvinces();
            }
        },

        // 打开编辑地址模态框并填充数据
        async editAddress(addr) {
            console.log('编辑地址:', addr);
            // 初始化编辑数据
            this.currentAddress = { ...addr };
            this.editMode = true; // 设置为编辑模式
            this.showModal = true;

            // 解析region字符串，填充省市区字段
            if (this.currentAddress.region) {
                const regionParts = this.currentAddress.region.split(' ');
                if (regionParts.length >= 1) this.currentAddress.province = regionParts[0];
                if (regionParts.length >= 2) this.currentAddress.city = regionParts[1];
                if (regionParts.length >= 3) this.currentAddress.district = regionParts[2];
            }
            console.log('当前地址:', this.currentAddress);

            // 根据已有的省份加载城市
            if (this.currentAddress.province) {
                $.ajax({
                    url: "http://localhost:8080/api/city",
                    type: 'GET',
                    data: { pname: this.currentAddress.province },
                    headers: { 'token': `${localStorage.getItem('token') || ''}` },
                    success: (cityRes) => {
                        // console.log('province:', this.currentAddress.province);
                        // console.log('city:', this.currentAddress.city);
                        this.cities = cityRes.list;
                        // 根据已有的城市加载区县
                        if (this.currentAddress.city) {
                            $.ajax({
                                url: "http://localhost:8080/api/area",
                                type: 'GET',
                                data: { pname: this.currentAddress.province, cname: this.currentAddress.city },
                                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                                success: (districtRes) => {
                                    // console.log('区县数据:', districtRes);
                                    this.districts = districtRes.list;
                                }
                            });
                        } else {
                            this.districts = [];
                        }
                    }
                });
            } else {
                // 如果没有省份信息，清空城市和区县下拉框
                this.cities = [];
                this.districts = [];
            }
            // 确保省份下拉框加载了数据
            if (this.provinces.length === 0) {
                this.loadProvinces();
            }
        },

        // 弹出删除确认弹窗，并记录要删除的地址
        confirmDelete(addr) {
            console.log('准备删除地址:', addr);
            this.addressToDelete = addr;
            this.showDeleteModal = true;
        },

        // 执行删除地址
        doDelete() {
            if (!this.addressToDelete || !this.addressToDelete.addressId) {
                console.error('没有要删除的地址或地址ID');
                this.showDeleteModal = false;
                return;
            }
            $.ajax({
                url: `http://localhost:8080/address/deleteAddress/${this.addressToDelete.addressId}`,
                type: 'DELETE',
                dataType: 'json',
                headers: {
                    'token': `${localStorage.getItem('token') || ''}`
                },
                success: (res) => {
                    if (res.code === 200) {
                        // 从本地列表中移除已删除的地址
                        this.addresses = this.addresses.filter(a => a.addressId !== this.addressToDelete.addressId);
                        alert('删除成功');
                    } else {
                        alert('删除失败：' + res.message);
                    }
                    this.showDeleteModal = false;
                    this.addressToDelete = null;
                },
                error: (xhr, status, error) => {
                    alert('网络错误，删除失败');
                    console.error('AJAX error deleting address:', status, error);
                    this.showDeleteModal = false;
                    this.addressToDelete = null;
                }
            });
        },

        // 保存地址
        saveAddress() {
            const url = this.editMode ? '/updateAddress' : '/addAddress';
            const method = 'POST';

            // 组织要发送到后端的数据
            const addressData = {
                ...this.currentAddress,
                region: `${this.currentAddress.province || ''} ${this.currentAddress.city || ''} ${this.currentAddress.district || ''}`.trim(),
                userId: localStorage.getItem('userId') || '',
            };

            $.ajax({
                url: "http://localhost:8080/address" + url,
                type: method,
                contentType: 'application/json',
                data: JSON.stringify(addressData),
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                dataType: 'json',
                success: (res) => {
                    if (res.code === 200) {
                        alert(this.editMode ? '地址更新成功' : '新地址添加成功');
                        this.showModal = false;
                        this.fetchAddresses();
                    } else {
                        alert('操作失败：' + res.message);
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，保存失败', status, err);
                }
            });
        },

        setDefault(addressId) {
            $.ajax({
                url: 'http://localhost:8080/address/setDefault',
                type: 'POST',
                data: {
                    userId: localStorage.getItem('userId') || '',
                    addressId: addressId
                },
                headers: {
                    'token': `${localStorage.getItem('token') || ''}`
                },
                dataType: 'json',
                success: (res) => {
                    if (res.code === 200) {
                        this.isDefault = true;
                        this.fetchAddresses(); // 重新加载地址列表
                    }
                },
                error: (xhr, status, error) => {
                    console.error('设置默认地址失败:', status, error);
                    alert('设置默认地址失败，请稍后再试');
                }
            })
        },
    },


    created() {
        this.fetchAddresses();
        this.loadProvinces();
    }
});